<template>
  <el-dialog :visible.sync="visible" v-if="visible" title="修改密码">
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" disabled/>
      </el-form-item>
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="formData.oldPassword" show-password placeholder="请输入原密码"/>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input v-model="formData.password" show-password placeholder="请输入新密码"/>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="formData.confirmPassword" show-password placeholder="请再次输入密码"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button type="warning" @click="visible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
const formData = {
  id: '',
  username: '',
  password: '',
  oldPassword: '',
  confirmPassword: ''
}
export default {
  name: 'UserinfoPassword',
  data () {
    return {
      visible: false,
      formData,
      rules: {
        oldPassword: [{
          required: true,
          message: '原密码不能为空'
        }],
        password: [{
          required: true,
          message: '新密码不能为空'
        }],
        confirmPassword: [{
          required: true,
          message: '确认密码不能为空'
        }, {
          validator: (rule, value, callback) => {
            if (value === this.formData.password) {
              callback()
            } else {
              callback(new Error('两次密码不一致'))
            }
          }
        }]
      }
    }
  },
  methods: {
    init (id) {
      this.visible = true
      this.formData = { ...formData }
      if (id) {
        this.$http.get(`userinfo/info/${id}`).then(data => {
          if (data) {
            this.formData = { ...formData, username: data.username, id: data.id }
          }
        })
      }
    },
    submit () {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.$http.post('userinfo/password', this.formData).then(() => {
            this.$alert('修改密码成功，请重新登录！', { type: 'success' }).then(() => {
              this.visible = false
              this.$cookies.remove('token')
              this.$router.replace('/')
            })
          }).catch(() => {})
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
